package com.yunkaweilai.android.fragment.order;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.web.WebActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.model.member.MemberConsumeRecordModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 消费记录
 * Created by Administrator on 2017/8/4.
 */

public class OrderConsumptionFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {
    @BindView(R.id.id_listView)
    ListView idListView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    Unbinder unbinder;
    private int mpage = 1;
    private boolean mHasMore = true;
    private Gson gson = new Gson();
    private ArrayList<MemberConsumeRecordModel.DataBean.ListBean> list = new ArrayList<>();
    private CommonAdapter<MemberConsumeRecordModel.DataBean.ListBean> adapter;
    @Override
    public int getContentViewId() {
        return R.layout.fragment_list;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initRefreshLayout(contentView, this, true);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp(true);
            }
        });
        initAdapter();
        initClick();
        initHttp(true);
    }

    private void initClick() {
        idListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MemberConsumeRecordModel.DataBean.ListBean listBean = list.get(position);
                WebActivity.actionStart(mAc,Api.BASE_URL + "index.php/app/OrderInfoView.html?tid="+listBean.getTid() +
                        "&token=" + BaseApplication.getToken());
            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<MemberConsumeRecordModel.DataBean.ListBean>(mAc,R.layout.item_list_operation_home,list) {
            @Override
            protected void convert(ViewHolder viewHolder, MemberConsumeRecordModel.DataBean.ListBean item, int position) {
                viewHolder.setText(R.id.id_tv_order_no, item.getStrconsume_type() + "：" + item.getTid());
                if (StringUtils.isEmpty(item.getCard_no())){
                    viewHolder.setText(R.id.id_tv_name,"散客");
                }else{
                    viewHolder.setText(R.id.id_tv_name,item.getMember_name()+" (" + item.getLevel_name() + ")");
                }
                viewHolder.setText(R.id.id_tv_time,item.getCreate_time()+"");
                viewHolder.setText(R.id.id_tv_price,item.getS_payment()+"");
            }
        };
        idListView.setAdapter(adapter);
    }

    private boolean initHttp(final boolean refresh) {
        mpage = refresh ? 1 : mpage;
        if ((!mHasMore) && (!refresh)) {
            contentView.endLoadingMore();
            showToast("没有更多数据了");
            return false;
        }
        HttpRequest.postUrl(Api.MEMBER_CONSUME_RECORD)
                .addParams("ShowPage", "1")
                .addParams("PageSize", "10")
                .addParams("CurrPage", mpage + "")
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(refresh);
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            mpage++;
                            MemberConsumeRecordModel consumeModel = gson.fromJson(json, MemberConsumeRecordModel.class);
                            if (refresh) {
                                list.clear();
                            }
                            if (consumeModel.getData().getList() != null && consumeModel.getData().getList().size() != 0) {
                                list.addAll(consumeModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                mHasMore = consumeModel.getData().getPage().isNext();//是否还有下一页
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                mHasMore = false;
                                if (refresh) {
                                    if (idMultipleStatusView != null) {
                                        idMultipleStatusView.showEmpty();
                                    }
                                }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });

        return true;
    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null){
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null){
                contentView.endLoadingMore();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initHttp(true);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return initHttp(false);
    }
}
